package com.yl.ydk.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import com.yl.ydk.base.BaseEvenBus
import com.yl.ydk.utils.L
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

class WifiBroadcastReceiver  : BroadcastReceiver(){

    override fun onReceive(context: Context?, intent: Intent?) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

        if (WifiManager.WIFI_STATE_CHANGED_ACTION == intent?.action) {
            //wifi开关变化
            when (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0)) {
                WifiManager.WIFI_STATE_DISABLED -> {
                    L.e( "已经关闭")
                }
                WifiManager.WIFI_STATE_DISABLING -> {
                    L.e( "正在关闭")
                }
                WifiManager.WIFI_STATE_ENABLED -> {
                    L.e( "已经打开")
                }
                WifiManager.WIFI_STATE_ENABLING -> {
                    L.e( "正在打开")
                }
                WifiManager.WIFI_STATE_UNKNOWN -> {
                    L.e( "未知状态")
                }
            }
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION == intent?.action) { //监听wifi连接状态
            val info = intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO)
            L.e("--NetworkInfo--" + info.toString())
            if (NetworkInfo.State.DISCONNECTED == info?.state) { //wifi没连接上
                L.e( "wifi没连接上")
                EventBus.getDefault().post(BaseEvenBus(BaseEvenBus.DISCONNECTED))
            } else if (NetworkInfo.State.CONNECTED == info?.state) { //wifi连接上了
                L.e("wifi已连接")
                EventBus.getDefault().post(BaseEvenBus(BaseEvenBus.CONNECTED))
            } else if (NetworkInfo.State.CONNECTING == info?.state) { //正在连接
                L.e("wifi正在连接")
                EventBus.getDefault().post(BaseEvenBus(BaseEvenBus.CONNECTING))
            }
        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION == intent?.action) {   //监听wifi列表变化
            L.e("wifi列表发生变化")
        }
    }

    @Subscribe
    fun evenbusMessage(baseEvenBus: BaseEvenBus) {

    }

}